package com.example.demo61jsonlogin.controller;

import com.example.demo61jsonlogin.domain.LoginBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
public class LoginController {

    @Autowired
    AuthenticationManager authenticationManager;

    /**
     * 自定义登录接口实现 json 登录
     */
    @PostMapping("/login")
    public String login(@RequestBody LoginBody loginBody, HttpSession session){
        UsernamePasswordAuthenticationToken unauthenticated = UsernamePasswordAuthenticationToken.unauthenticated(loginBody.getUsername(), loginBody.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(unauthenticated);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            // HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY : SPRING_SECURITY_CONTEXT
            // 手动将 SecurityContext 存入 session
            session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
            return "success";
        } catch (AuthenticationException e) {
            return "error: " + e.getMessage();
        }
    }

}
